package cn.hbu.zlfw.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import cn.hbu.zlfw.common.util.SessionUtil;
import cn.hbu.zlfw.common.util.ZLFWConstants;
import cn.hbu.zlfw.system.controller.AdminUserController;
/**
 * 
 *@ClassName:LoginInterceptor.java
 *@Description:  登录验证拦截器
 *@Author:lxt<839376636@qq.com>
 *@Date:2017年10月9日下午9:12:12
 *@Version:1.1.0
 */
public class LoginInterceptor implements HandlerInterceptor{
	
	/**
	 * 日志
	 */
	public final Logger logger = LoggerFactory.getLogger(AdminUserController.class);
	

	/**
	 * 通过后缀名对url进行验证过滤吗，当后缀名为.action,.do时要进行登录验证
	 */
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("-----------------Interceptor----------------------");
		int flag = ZLFWConstants.ERROR_URL_SUFFIX;	
		//获取url
		String url = request.getRequestURL().toString();
		logger.debug("请求路径："+url);
		Object object = SessionUtil.getLoginUser(request);
		if(url.contains(ZLFWConstants.IS_LOGIN_SUFFIX)) {
			logger.debug("session存储对象："+object);
			flag = object == null?ZLFWConstants.USER_LOGIN_FALSE:ZLFWConstants.LOGIN_TRUE;
		} else if(url.contains(ZLFWConstants.IS_ADMIN_LOGIN_SUFFIX)) {
			logger.debug("session存储对象："+object);
			flag = object == null?ZLFWConstants.ADMIN_LOGIN_FALSE:ZLFWConstants.LOGIN_TRUE;
		} else if(url.contains(ZLFWConstants.NO_LOGIN_SUFFIX)) {
			//不需要登录验证
			flag = ZLFWConstants.NO_LOGIN;
		}
		/**
		 * 跳转到登录界面
		 */
		if(flag == ZLFWConstants.ADMIN_LOGIN_FALSE) {
			response.sendRedirect(ZLFWConstants.ADMIN_LOGIN_PAGE);
			return false;
		} else if (flag == ZLFWConstants.USER_LOGIN_FALSE) {
			response.sendRedirect(ZLFWConstants.USER_LOGIN_PAGE);
			return false;
		} else if (flag == ZLFWConstants.LOGIN_TRUE || flag == ZLFWConstants.NO_LOGIN) {
			return true;
		} else {
			response.sendRedirect(ZLFWConstants.ERROR_404_PAGE);
			return false;
		}
	}

	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// TODO Auto-generated method stub
	}

	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub
	}

}
